<?php

/**
 * GrouponAddressController is the default controller for this application
 */
class GrouponAddressController extends ControllerBase {
	public $grouponAddressDataService = null;
	public function __construct() {
		parent::__construct ();
		$this->grouponAddressDataService = new GrouponAddressDataService ();
	}
	
	public function addAction() {
		$result = ERROR;
		$message = 'Thêm địa chỉ không thành công!';
		$name = $this->getPost ( 'name', '' );
		$address = $this->getPost ( 'address', '' );
		$city = $this->getPost ( 'city', '' );
		$phone = $this->getPost ( 'phone', '' );
		try {
			//get city name
			//thieu cho city
			//$city_name = 'Hồ Chí Minh';
			//get latitude
			$location = $this->grouponAddressDataService->getlatitude ( $address . '+,' . $name . '+, Việt Nam' );
			
			$grouponAddressEntity = $this->grouponAddressDataService->beforeCreate ();
			$grouponAddressEntity->name = $name;
			$grouponAddressEntity->address = $address;
			$grouponAddressEntity->city_id = $city;
			$grouponAddressEntity->phone = $phone;
			$grouponAddressEntity->lat = $location ['lat'];
			$grouponAddressEntity->lng = $location ['lng'];
			
			$this->grouponAddressDataService->create ( $grouponAddressEntity );
			$result = SUCC;
		} catch ( Exception $e ) {
			$result = ERROR;
		}
		$rturn = array ("error" => $result, "message" => $message );
		
		echo Zend_Json::encode ( $rturn );
		exit ();
	}
	public function editAction() {
		$add_id = $this->getQuery ( 'add_id', 0 );		
		$adddressEntity = $this->grouponAddressDataService->getById($add_id);
		$cityDataSevice =  new CityDataService();
		$cityList = $cityDataSevice->getItems(array());
		$this->smarty->assign('cityList', $cityList);
		$this->smarty->assign ( 'adddressEntity', $adddressEntity );
		$this->smarty->display ( 'Admin/GrouponAddress/edit.tpl' );
	}
	public function doEditAction(){
	$add_id = $this->getPost ( 'add_id', 0 );	
		$adddressEntity = $this->grouponAddressDataService->getById($add_id);
		$action = $this->getPost('submit','');
		if($action == 'submit'){
			$adddressEntity->name = $this->getPost('name', '');
			$adddressEntity->address = $this->getPost('address', '');
			$adddressEntity->phone = $this->getPost('phone', '');
			$adddressEntity->city = $this->getPost('city', '');
			$this->grouponAddressDataService->update($adddressEntity);
		}
		//echo Zend_Json::encode ( array ('success' => 1 ) );
		//exit ();
		$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Admin/Groupon/add';
		CommonUtils::redirect ( $url );
		return - 1;
	}
	public function getallAction() {
		$listAddress = $this->grouponAddressDataService->getItems ( array () );
		$return = array ();
		$i = 0;
		foreach ( $listAddress as $item ) {
			$return [$i] ['id'] = $item->id;
			$return [$i] ['name'] = $item->name;
			$i ++;
		}
		echo Zend_Json::encode ( $return );
		exit ();
	}
}
